package com.fsq.config;

import com.alibaba.fastjson.JSONObject;
import com.fsq.token.UserToken;
import com.fsq.util.JwtTokenUtil;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author fsq
 * @date 2020/07/28
 */
public class AuthenticationInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从http请求头中取出token
        final String token = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        //如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //如果是方法探测，直接通过
        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        if (ObjectUtils.isEmpty(token)) {
            return Boolean.FALSE;
        }
        //验证，并获取token内部信息
        String result = JwtTokenUtil.verifyToken(token);

        // 写死验证自己的手机
        Object o = JSONObject.parse(result);
        if (o instanceof UserToken) {
            if ("18316102612".equals(((UserToken) o).getPhone())) {
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }
}
